package com.gxa.educate.core.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * @author yuxuanzhen
 * @date 2022/7/7 18:32
 */
public class RestUtils {
    private static RestTemplate restTemplate;

    static {
        restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

    public static Map postWithParams(String url, Map<String,String>headers, MultiValueMap params){
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        if (headers!=null){
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                httpHeaders.set(entry.getKey(),entry.getValue());
            }
        }
        HttpEntity httpEntity=new HttpEntity<>(params,httpHeaders);
        Map map = restTemplate.postForObject(url, httpEntity, Map.class);
        return map;
    }

    public static Map postWithParams(String url, MultiValueMap params){

        Map map = postWithParams(url, null, params);
        return map;
    }

}
